<?php declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\JobCategory;
use app\admin\model\Job;
use think\facade\Log;

class JobCategoryService
{
    /**
     * 岗位分类
     * @return mixed
     */
    public function getJobCategoryList(){
        $model = new JobCategory();
        return $model->where(['is_delete'=>0])->order(['sort','id'=>'desc'])->paginate(100000);
    }

    /**
     * 获取分类
     * @param int $level
     * @return void
     */
    public function getJobCategory(int $level = 0){
        $model = new JobCategory();
        return $model->field('id,name')->where('parent_id', $level)->select();
    }

    /**
     * 获取分类id
     * @param int $parentId
     * @return void
     */
    public function getJobCategoryId(int $parentId){
        $model = new JobCategory();
        return $model->where('parent_id', $parentId)->value('parent_id');
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        if (empty($data)) {
            return false;
        }
        $model = new JobCategory();
        try {
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit JobCategory error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 获取分类
     * @param int $id
     * @return void
     */
    public function getJobCategoryBy(int $id){
        $model = new JobCategory();
        return $model->find($id);
    }

    /**
     * 删除分类
     * @param int $id
     * @return void
     */
    public function delete(int $id){
        try {
            $model = new JobCategory();
            $item = $model->find($id);
            if (empty($item)) {
                return json(['code'=>1, 'msg'=>'记录不存在，删除失败']);
            }
            $jobModel = new Job();
            $childJobCategory = $model->where([ 'parent_id'=>$id, 'is_delete'=>0 ])->find();
            $jobItems = $jobModel->where(['status'=>1,'is_delete'=>0, 'category_id'=>$id])->find();
            if($childJobCategory || $jobItems){
                return json(['code'=>1, 'msg'=>'该岗位分类下含有子分类或存在已发布的职位，禁止删除']);
            } else{
                $item->save(['is_delete'=>1, 'create_time'=>time()]);
                return json(['code'=>0, 'msg'=>'删除成功']);
            }
        } catch (\Exception $e) {
            Log::error("delete JobCategory failed:" .$e->getMessage());
            return json(['code'=>1, 'msg'=>'删除失败']);
        }
    }
}